package com.example.yiwei.crm.view.activity.contactActivity;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.customerDao;
import com.example.yiwei.crm.dao_impl.customerDaoImpl;
import com.example.yiwei.crm.data.GetContact;
import com.example.yiwei.crm.data.GetContactData;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.entity.ContactMessageEntity;
import com.example.yiwei.crm.util.NetWorkUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ContactAddMessageActivity extends AppCompatActivity {
ImageView img_commt,img_back;
    EditText edit_contact_name,edit_respectful,edit_contact_job,edit_contact_address,
            edit_belongs_to_customer,edit_contact_phone,edit_contact_email,edit_zip_code,edit_additional;
    ContactMessageEntity contact;
    String tag;
    RelativeLayout relativeLayout;
    int client_id;
    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCiry = new ArrayList<ArrayList<String>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();
    private OptionsPickerView<String> mOpv;
    private JSONObject mJsonObj;
    private String Filename;
    private TextView mtCity;
    private RadioGroup rg_sex;
    private RadioButton rb_men,rb_women;
    Button btn_find;
    String tx;
    int sex;
    TextView txt_address;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_add_message);
        relativeLayout= (RelativeLayout) findViewById(R.id.relative_belongs_customer);
        img_back= (ImageView) findViewById(R.id.contact_add__img_back);
        img_commt= (ImageView) findViewById(R.id.contact_add_img_commit);
        edit_contact_address= (EditText) findViewById(R.id.contact_add_edit_detailed_addresss);
        edit_contact_phone= (EditText) findViewById(R.id.contact_add_edit_mobile_phone);
        edit_contact_name= (EditText) findViewById(R.id.contact_add_edit_name);
        edit_respectful= (EditText) findViewById(R.id.contact_add_edit_respectful);
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i==rb_men.getId()){
                    sex=1;
                }else{
                    sex=2;
                }
            }
        });
        contact= GetContact.get();
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  finish();
            }
        });
        img_commt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  add();
            }
        });
        Intent intent=getIntent();
        tag=intent.getStringExtra("tag");
        if (getIntent().getStringExtra("cTag")!=null){
            if ("create".equals(getIntent().getStringExtra("cTag"))){
              client_id= GetCustumer.customers.getClient_id();
                relativeLayout.setVisibility(View.GONE);
            }
        }
        if(tag!=null){
            if ("update".equals(tag)){
                initData();
            }
        }
        initJsonData(this);
        // 初始化Json数据
        initJsonDatas();
        // 创建选项选择器对象
        mOpv = new OptionsPickerView<String>(this);

        // 设置标题
        mOpv.setTitle("选择城市");

        // 设置三级联动效果
        mOpv.setPicker(mListProvince, mListCiry, mListArea, true);

        // 设置是否循环滚动
        mOpv.setCyclic(false, false, false);

        // 设置默认选中的三级项目
        mOpv.setSelectOptions(0, 0, 0);

        // 监听确定选择按钮
        mOpv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                // 返回的分别是三个级别的选中位置
                tx = mListProvince.get(options1) + mListCiry.get(options1).get(option2) + mListArea.get(options1).get(option2).get(options3);
                txt_address.setText(tx);
            }
        });
        // 点击弹出选项选择器
        btn_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOpv.show();
            }
        });

    }
    public void initData(){
        edit_contact_email.setText(contact.getContact_email());
        if(contact.getContact_gender()==1){
            rb_men.setChecked(true);
        }else if (contact.getContact_gender()==2){
            rb_women.setChecked(true);
        }
        edit_additional.setText(contact.getContact_additional());
        edit_contact_name.setText(contact.getContact_name());
        edit_respectful.setText(contact.getContact_respectful());
        edit_contact_job.setText(contact.getContact_job());
        edit_belongs_to_customer.setText(contact.getFirst_contact_name());
        edit_contact_email.setText(contact.getContact_email());
        edit_zip_code.setText(contact.getContact_zip_code());
        edit_contact_address.setText(contact.getContact_address());
        edit_contact_phone.setText(contact.getContact_mobile_phone());
    }
    public void add(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject json=new JSONObject();
                String sresult ="";
                try {
                    if (client_id!=0){
                        json.put("KAA01",client_id);
                    }
                    json.put("REK01",edit_additional.getText().toString());
                    if(tx!=null){
                        json.put("KLA13",tx+edit_contact_address.getText().toString());
                    }else{
                        json.put("KLA13",edit_contact_address.getText().toString());
                    }

                    json.put("KLA09",edit_zip_code.getText().toString());
                    json.put("KLA08",edit_contact_email.getText().toString());
                    json.put("KLA06",edit_contact_phone.getText().toString());
//                    json.put("KAA01",Integer.valueOf(edit_belongs_to_customer.getText().toString()));
                    json.put("KLA03", sex);
                    json.put("KLA05",edit_contact_job.getText().toString());
                    json.put("KLA04",edit_respectful.getText().toString());
                    json.put("KLA02",edit_contact_name.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if ("update".equals(tag)){
                    try {
                        json.put("KLA01",contact.getContact_id());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    String sjson=json.toString();
                    sresult= NetWorkUtils.getCount(baseClass.update_contact_message,sjson);

                }else {
                    String sjson = json.toString();
                    sresult = NetWorkUtils.getCount(baseClass.add_contact_message_url, sjson);
                }
                JSONObject object = null;
                try {
                    object = new JSONObject(sresult);
                    String boolen = object.getString("boolean");
                    if (boolen.toString().equals("success")) {
                        customerDao customerdao = new customerDaoImpl();
                        List<ContactMessageEntity> contactMessageEntities = customerdao.queryContactAllMessage(baseClass.queryall_contact_message_url, null);
                        GetContactData.creatData();
                        GetContactData.contacts = contactMessageEntities;
                        if (GetContactData.contacts != null) {
                            setData();
                            finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    public void setData(){
        contact.setContact_mobile_phone(edit_contact_phone.getText().toString());
        contact.setContact_additional(edit_additional.getText().toString());
        contact.setContact_email(edit_contact_email.getText().toString());
        contact.setContact_gender(sex);
        contact.setContact_name(edit_contact_name.getText().toString());
        contact.setContact_respectful(edit_respectful.getText().toString());
        contact.setContact_job(edit_contact_job.getText().toString());
        contact.setFirst_contact_name(edit_belongs_to_customer.getText().toString());
        contact.setContact_zip_code(edit_zip_code.getText().toString());
        if(tx!=null){
            contact.setContact_address(tx+edit_contact_address.getText().toString());
        }else{
            contact.setContact_address(edit_contact_address.getText().toString());
        }
    }
    /** 从assert文件夹中读取省市区的json文件，然后转化为json对象 */
    private void initJsonData(Context context) {
        Filename = "city.json";
        try {
            StringBuffer sb = new StringBuffer();
            AssetManager am = context.getAssets();
            InputStream is = am.open(Filename);
            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "GBK"));
            }
            is.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /** 初始化Json数据，并释放Json对象 */
    private void initJsonDatas(){
        try {
            JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 获取每个省的Json对象
                String province = jsonP.getString("name");
                ArrayList<String> options2Items_01 = new ArrayList<String>();
                ArrayList<ArrayList<String>> options3Items_01 = new ArrayList<ArrayList<String>>();
                JSONArray jsonCs = jsonP.getJSONArray("city");
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonC = jsonCs.getJSONObject(j);// 获取每个市的Json对象
                    String city = jsonC.getString("name");
                    options2Items_01.add(city);// 添加市数据
                    ArrayList<String> options3Items_01_01 = new ArrayList<String>();
                    JSONArray jsonAs = jsonC.getJSONArray("area");
                    for (int k = 0; k < jsonAs.length(); k++) {
                        options3Items_01_01.add(jsonAs.getString(k));// 添加区数据
                    }
                    options3Items_01.add(options3Items_01_01);
                }
                mListProvince.add(province);// 添加省数据
                mListCiry.add(options2Items_01);
                mListArea.add(options3Items_01);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }
}
